package com.crm.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crm.business.domain.TbBusiness;
import com.crm.business.mapper.BusinessMapper;
import com.crm.common.constant.ClueConstants;
import com.crm.common.core.domain.entity.SysUser;
import com.crm.common.domain.vo.AssignMentVo;
import com.crm.common.utils.DateUtils;
import com.crm.domain.Activity;
import com.crm.domain.AssignRecord;
import com.crm.domain.Clue;
import com.crm.domain.FalseClue;
import com.crm.domain.dto.GainDto;
import com.crm.domain.dto.PageAndTimeClueDto;
import com.crm.mapper.ActivityMapper;
import com.crm.mapper.AssignRecordMapper;
import com.crm.mapper.ClueMapper;
import com.crm.mapper.FalseClueMapper;
import com.crm.service.IClueService;
import com.crm.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.crm.common.utils.SecurityUtils;

import java.util.Date;
import java.util.List;

@Service
public class ClueServiceImpl implements IClueService {
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private AssignRecordMapper assignRecordMapper;
    @Autowired
    private FalseClueMapper falseClueMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 分页条件查询线索列表
     *
     * @param pageAndTimeClueDto
     * @return
     */
    @Override
    public List<Clue> pageWithCreatTime(PageAndTimeClueDto pageAndTimeClueDto) {
        List<Clue> clueList = clueMapper.pageWithCreatTime(pageAndTimeClueDto);
        for (Clue clue : clueList) {
            if (clue != null && clue.getActivityId() != null) {
                // 该线索不为空且有活动id
                Activity activity = activityMapper.getActivityById(clue.getActivityId());
                if (activity != null) {
                    // 活动不为空,给线索对象的活动名称赋值
                    clue.setActivityInfo(activity.getInfo());
                    clue.setActivityName(activity.getName());
                }
            }
        }
        return clueList;
    }

    /**
     * 添加线索
     *
     * @param clue
     */
    @Override
    public void add(Clue clue) {
        clue.setOwner(SecurityUtils.getUsername());
        clue.setOwnerTime(new Date());
        clueMapper.insert(clue);
    }

    /**
     * 根据id查询线索
     *
     * @param id
     * @return
     */
    @Override
    public Clue getById(Long id) {
        // 通过线索id查找
        Clue clue = clueMapper.selectOne(Wrappers.<Clue>lambdaQuery().eq(Clue::getId, id));
        if (clue != null && clue.getActivityId() != null) {
            // 该线索不为空且有活动id
            Activity activity = activityMapper.getActivityById(clue.getActivityId());
            if (activity != null) {
                // 活动不为空,给线索对象的活动名称赋值
                clue.setActivityInfo(activity.getInfo());
                clue.setActivityName(activity.getName());
            }
        }
        // 查询派遣信息,type=0为线索,派遣数据中assignid为线索id
        Long clueId = clue.getId();
        List<AssignRecord> assignRecord = assignRecordMapper.selectByAssignId(clueId, "0");
        // 证明是待分配数据
        if (assignRecord == null || assignRecord.size() == 0) {
            return clue;
        }
        clue.setOwner(assignRecord.get(0).getUserName());
        clue.setOwnerTime(assignRecord.get(0).getCreateTime());
        return clue;
    }

    /**
     * 添加伪线索记录
     *
     * @param id
     * @param falseClue
     */
    @Override
    public void addFalseClue(Long id, FalseClue falseClue) {
        // 给线索的判断为伪线索计数+1
        clueMapper.falseCountAdd(id);
        // 查询已经有过几次伪线索次数了
        Integer falseCount = clueMapper.selectOne(Wrappers.<Clue>lambdaQuery().eq(Clue::getId, id)).getFalseCount();
        if (falseCount >= 3) {
            // 直接删除该线索
            clueMapper.deleteById(id);
            falseClueMapper.delete(Wrappers.<FalseClue>lambdaQuery().eq(FalseClue::getClueId, id));
            return;
        }
        // 存入伪线索记录
        falseClue.setClueId(id);
        falseClueMapper.insert(falseClue);
        // 将该线索推入线索池
        clueMapper.pushInPool(id);
    }

    /**
     * 捞取线索
     *
     * @param gainDto
     */
    @Override
    public void scooping(GainDto gainDto) {
        // 遍历接收到的线索id从线索池中取出线索
        Long[] ids = gainDto.getIds();
        for (Long id : ids) {
            // 获取线索
            Clue clue = clueMapper.selectOne(Wrappers.<Clue>lambdaQuery().eq(Clue::getId, id));
            // 将线索状态改为待跟进状态
            clue.setStatus(ClueConstants.TO_BE_FOLLOWED);
            // 将线索的负责人改为捞取人
            String userName = SecurityUtils.getUsername();
            clue.setOwner(userName);
            clue.setOwnerTime(new Date());
            // 更新线索
            clueMapper.updateById(clue);
            // 添加分配记录
            AssignRecord assignRecord = new AssignRecord();
            assignRecord.setAssignId(id);
            assignRecord.setUserId(gainDto.getUserId());
            // 将关联的负责人初始化为捞取人
            assignRecord.setUserName(userName);
            assignRecord.setDeptId(SecurityUtils.getDeptId());
            assignRecord.setCreateBy(userName);
            assignRecord.setCreateTime(new Date());
            // 默认是最新
            assignRecord.setLatest("1");
            // 这里是线索
            assignRecord.setType("0");
            assignRecordMapper.add(assignRecord);
        }
    }

    /**
     * 线索转为商机
     *
     * @param id
     */
    @Override
    public void changeBusiness(Long id) {
        // 取出线索
        Clue clue = clueMapper.selectOne(Wrappers.<Clue>lambdaQuery().eq(Clue::getId, id));
        // 创建商机对象
        TbBusiness business = new TbBusiness();
        // 除了id,赋值给商机对象
        BeanUtils.copyProperties(clue, business);
        business.setId(null);
        // 存入商机数据库
        businessMapper.insert(business);
        // 从数据库删除该线索
        clueMapper.deleteById(id);
    }

    /**
     * 分配线索
     *
     * @param assignMentVo
     */
    @Override
    public void assignment(AssignMentVo assignMentVo) {
        List<Long> ids = assignMentVo.getIds();
        for (Long id : ids) {
            Clue clue = clueMapper.selectById(id);
            SysUser sysUser = sysUserService.selectUserById(assignMentVo.getUserId());
            clue.setOwner(sysUser.getUserName());
            clue.setUpdateBy(SecurityUtils.getUsername());
            clue.setOwnerTime(DateUtils.getNowDate());
            clueMapper.updateById(clue);
        }
    }
}
